package com.soujiayi.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.soujiayi.model.TuanCity;
import com.soujiayi.net.EmailSender;
import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.store.SPResolver;
import com.soujiayi.util.Constants;
import com.soujiayi.util.Encryptor;
import com.soujiayi.util.SystemInfoUtil;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.WindowManager;

public class SplashActivity extends Activity {

	private long delayTime = 3000;
	private int INIT = 1;
	long start, end;
	private DatabaseManager databaseManager = new DatabaseManager(
			SplashActivity.this);

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub

			if (msg.what == INIT) {
				end = System.currentTimeMillis();
				if (end - start < delayTime) {
					handler.postDelayed((new Runnable() {
						public void run() {
							Intent intent = new Intent(SplashActivity.this,
									IndexActivity.class);
							startActivity(intent);
							SplashActivity.this.finish();
						}
					}), delayTime - end + start);
				} else {
					handler.post((new Runnable() {
						public void run() {
							Intent intent = new Intent(SplashActivity.this,
									IndexActivity.class);
							startActivity(intent);
							SplashActivity.this.finish();
						}
					}));
				}
			}

		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.splash);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		start = System.currentTimeMillis();
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (NetworkUtils.isNetworkConnected(SplashActivity.this)) {
					initSessionId();
					checkOnlineUser();
					uploadCrashLog();
				}
				Message msg = new Message();
				msg.what = INIT;
				handler.sendMessage(msg);
			}
		}).start();
	}

	public void checkOnlineUser() {
		User user = databaseManager.getOnlineUser();
		if (user != null) {
			HashMap<String, String> parameters = new HashMap<String, String>();
			parameters.put("sid", ((MyApplication) SplashActivity.this
					.getApplication()).getSessionId());
			parameters.put("uid", String.valueOf(user.getUid()));
			HttpRequester httpRequester = new HttpRequester(this);
			User memberInfo = httpRequester.getMemberInfo(parameters, true);
			if (memberInfo != null) {
				UserKeeper.keepUser(SplashActivity.this, memberInfo,
						Constants.PREFERENCES_NAME_USER);
			} else {
				UserKeeper.keepUser(SplashActivity.this, user,
						Constants.PREFERENCES_NAME_USER);
			}
			String type = "goods";
			parameters.put("type", type);
			List<Map<String, String>> list = httpRequester.getFavorite(
					parameters, true);
			if (list != null && list.size() > 0) {
				databaseManager.deleteAllFavorites(type);
				databaseManager.insertFavorites(list, type);
			}

		}

		List<User> sharedUsers = databaseManager.getShareUser();
		for (int i = 0; i < sharedUsers.size(); i++) {
			User sharedUser = sharedUsers.get(i);
			if (sharedUser.getType() == Constants.USER_TYPE_SINA) {
				if (Long.parseLong(sharedUser.getSina_expires_time()) < System
						.currentTimeMillis()) {
					UserKeeper.keepUser(SplashActivity.this, sharedUser,
							Constants.PREFERENCES_NAME_USER_SINA);
				} else {
					databaseManager.deleteShareUser(sharedUser.getType());
				}
			} else if (sharedUser.getType() == Constants.USER_TYPE_TENCENT) {
				if (Long.parseLong(sharedUser.getTencent_expires_time()) < System
						.currentTimeMillis()) {
					UserKeeper.keepUser(SplashActivity.this, sharedUser,
							Constants.PREFERENCES_NAME_USER_TENCENT);
				} else {
					databaseManager.deleteShareUser(sharedUser.getType());
				}
			}
		}

	}

	public void initSessionId() {
		SPResolver spr = new SPResolver(this, Constants.SP_SYSTEM,
				Context.MODE_PRIVATE);
		spr.OpenEditor();
		String systemId = Encryptor.MD5Encript(SystemInfoUtil.getSysInfo(this)
				.toString());
		String tem_systemId = spr.getValue(Constants.SP_SYSTEM_ID, "");
		String tem_sessionId = spr.getValue(Constants.SP_SESSION_ID, "");
		if (!systemId.equals(tem_systemId) || "".equals(tem_sessionId)) {
			String sessionId = new HttpRequester(this).buildSessionId();
			spr.putValue(Constants.SP_SYSTEM_ID, systemId);
			spr.putValue(Constants.SP_SESSION_ID, sessionId);
			spr.commitEditor();
			spr.closeEditor();
			((MyApplication) this.getApplication()).setSessionId(sessionId);
		} else
			((MyApplication) this.getApplication()).setSessionId(tem_sessionId);

	}

	public void uploadCrashLog() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File dir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					Constants.CRASH_DIR);
			if (!dir.exists())
				dir.mkdirs();
			File[] fileList = dir.listFiles();

			if (fileList != null && fileList.length > 0) {

				Arrays.sort(fileList, new LastModifiedFileComparator());

				BufferedReader reader = null;
				try {
					reader = new BufferedReader(new FileReader(fileList[0]));
					String tempString = null;
					StringBuffer sb = new StringBuffer();
					while ((tempString = reader.readLine()) != null) {
						// 显示行号
						sb.append(tempString);
					}
					reader.close();

					EmailSender sender = new EmailSender();
					// 设置服务器地址和端口，网上搜的到
					sender.setProperties(Constants.EMAILSENDER_SMTP_SERVER,
							Constants.EMAILSENDER_SMTP_PORT);
					// 分别设置发件人，邮件标题和文本内容
					sender.setMessage(Constants.EMAILSENDER_SENDER,
							this.getString(R.string.crash_mail_title),
							sb.toString());
					// 设置收件人
					sender.setReceiver(new String[] { Constants.EMAILSENDER_RECEIVER });
					// 发送邮件
					sender.sendEmail(Constants.EMAILSENDER_SMTP_SERVER,
							Constants.EMAILSENDER_SENDER,
							Constants.EMAILSENDER_SENDER_PASSWORD);
					for (int i = 0; i < fileList.length; i++)
						fileList[i].delete();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (reader != null) {
						try {
							reader.close();
						} catch (IOException e1) {
						}
					}
				}
			}

		}
	}

	public class LastModifiedFileComparator implements Comparator {
		@Override
		public int compare(Object object1, Object object2) {
			File file1 = (File) object1;
			File file2 = (File) object2;
			long result = file1.lastModified() - file2.lastModified();
			if (result < 0) {
				return -1;
			} else if (result > 0) {
				return 1;
			} else {
				return 0;
			}
		}
	}

}
